package com.aloda.utils;

import com.aloda.properties.FileUploadProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 本地文件上传
 */
@Component
public class FileUploadUtil {

    @Autowired
    private FileUploadProperties fileUploadProperties;

    public String saveFile(MultipartFile file) throws IOException {
        // Ensure the upload directory exists
        File uploadDir = new File(fileUploadProperties.getUploadPath());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // Generate a unique file name to avoid collisions
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        Path filePath = Paths.get(fileUploadProperties.getUploadPath(), fileName);

        // Save the file to the specified directory
        Files.write(filePath, file.getBytes());

        // Return the file URL
        return fileUploadProperties.getAccessPath() + "/"+fileName;
    }
}
